package com.vm.activity;

import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.adapter.FragAdapter;
import com.vm.commons.CurrentSetting;
import com.vm.commons.CurrentSoft;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.CollectionDao;
import com.vm.fragment.IntroduceFragment;
import com.vm.fragment.SoftCommentsFragment;
import com.vm.fragment.UIHelper;
import com.vm.model.Collection;
import com.vm.model.Soft;
import com.vm.myview.NoScrollViewPager;
import com.vm.utils.BitmapUtil;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.vm.utils.ThreadManager;
import com.wwtscapp.apk.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年1月30日 下午3:10:32]
 * @Version: [v1.0]
 * 
 */
@SuppressLint("ShowToast")
public class DetailActivity extends FragmentActivity {

	protected static final String TAG = "DetailActivity";

	RadioButton rbtn_comments;
	RadioButton rbtn_introduce;
	RadioButton rbtn_related;
	RequestQueue mQueue;

	ImageView imgbtn_search_back; // 返回按钮
	NoScrollViewPager nsvp;
	List<Fragment> fragments;
	private FragAdapter adapter;
	String softId;
	int isNow;
	int btnType;
	RatingBar rb_star;
	ImageView iv_collect;
	ImageView iv_collect1;
	Button btn_getIntergral;
	ImageView iv_softImage;
	TextView tv_softName;
	TextView tv_version;
	TextView tv_softdownload;
	TextView tv_soft_size;
	RelativeLayout rlayout_introduce;
	LinearLayout llayout_group;
	NoScrollViewPager viewpager;
	private CollectionDao cDao = null;
	public static Soft soft = new Soft();
	private Collection collection;
	List<Collection> list;
	RelativeLayout rl_detail;
	int a = 0;
	int addRecord;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		collection = new Collection();
		View view = View.inflate(this, R.layout.detail_page, null);
		setContentView(view);
		cDao = new CollectionDao(DetailActivity.this);
		softId = getIntent().getStringExtra("softId");
		isNow = getIntent().getIntExtra("isNow", 0);
		addRecord = getIntent().getIntExtra("addRecord", 0);
		btnType = getIntent().getIntExtra("btnType", 0);
		a = getIntent().getIntExtra("return", 0);
	}

	public void onResume() {
		init();
		initData();
		super.onResume();
	}

	private void initFragment() {
		fragments = new ArrayList<Fragment>();
		IntroduceFragment introFragment = new IntroduceFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable("soft", soft);
		bundle.putInt("addRecord", addRecord);
		introFragment.setArguments(bundle);
		SoftCommentsFragment softCommentsFragment = new SoftCommentsFragment();
		softCommentsFragment.setArguments(bundle);
		fragments.add(introFragment);
		fragments.add(softCommentsFragment);
		nsvp = (NoScrollViewPager) findViewById(R.id.viewpager);
		adapter = new FragAdapter(getSupportFragmentManager(), fragments);
		nsvp.setAdapter(adapter);

		// 设置最大缓存数
		// 默认缓存2个页面,当出现第三个页面会删掉之前缓存中的一个.
		nsvp.setOffscreenPageLimit(3);
		nsvp.setCurrentItem(0);
	}

	/**
	 * 初始化控件
	 */
	private void init() {

		// tv_version = (TextView) findViewById(R.id.tv_soft_versions);
		tv_softName = (TextView) findViewById(R.id.tv_softName);
		tv_softdownload = (TextView) findViewById(R.id.tv_softdownload);
		tv_soft_size = (TextView) findViewById(R.id.tv_soft_size);

		rbtn_introduce = (RadioButton) findViewById(R.id.rbtn_introduce);
		rbtn_comments = (RadioButton) findViewById(R.id.rbtn_comments);
		rbtn_related = (RadioButton) findViewById(R.id.rbtn_related);

		rbtn_introduce.setOnClickListener(btn_listener);
		rbtn_comments.setOnClickListener(btn_listener);
		rbtn_related.setOnClickListener(btn_listener);

		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
		rb_star = (RatingBar) findViewById(R.id.rb_star);
		btn_getIntergral = (Button) findViewById(R.id.btn_get_intergral);
		rlayout_introduce = (RelativeLayout) findViewById(R.id.rlayout_introduce);
		llayout_group = (LinearLayout) findViewById(R.id.llayout_group);
		viewpager = (NoScrollViewPager) findViewById(R.id.viewpager);
		iv_collect = (ImageView) findViewById(R.id.iv_collect);
		iv_collect1 = (ImageView) findViewById(R.id.iv_collect1);
		if (cDao.ifExits(softId)) {
			iv_collect.setVisibility(View.GONE);
			iv_collect1.setVisibility(View.VISIBLE);
		}
		iv_collect1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				collection.setImageurl(CurrentSoft.SOFTIMG);
				collection.setName(CurrentSoft.SOFTNAME);
				collection.setSize(CurrentSoft.SOFTSIZE);
				collection.setSoftId(CurrentSoft.SOFTID);
				collection.setStar(CurrentSoft.SOFTSTAR);
				cDao.delete(CurrentSoft.SOFTID);
				Toast toast = Toast.makeText(DetailActivity.this, "取消收藏",
						Toast.LENGTH_SHORT);
				toast.show();
				iv_collect.setVisibility(View.VISIBLE);
				iv_collect1.setVisibility(View.GONE);
			}
		});
		iv_collect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				collection.setImageurl(CurrentSoft.SOFTIMG);
				collection.setName(CurrentSoft.SOFTNAME);
				collection.setSize(CurrentSoft.SOFTSIZE);
				collection.setSoftId(CurrentSoft.SOFTID);
				collection.setStar(CurrentSoft.SOFTSTAR);
				cDao.insert(collection);
				list = cDao.selectall();
				Toast toast = Toast.makeText(DetailActivity.this, "收藏成功",
						Toast.LENGTH_SHORT);
				toast.show();
				iv_collect.setVisibility(View.GONE);
				iv_collect1.setVisibility(View.VISIBLE);
			}
		});
		/**
		 * 跳转到搜索页面
		 */
		ImageView iv_search = (ImageView) findViewById(R.id.iv_search);
		iv_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(DetailActivity.this,
				// SearchActivity.class);
				// startActivityForResult(intent, 10);
			}
		});
	}

	private void initData() {

		UIHelper.showDialogForLoading(this, "正在加载...", true);
		viewpager.setVisibility(View.INVISIBLE);
		rlayout_introduce.setVisibility(View.INVISIBLE);
		llayout_group.setVisibility(View.INVISIBLE);
		mQueue = MyVolley.getRequestQueue();

		String url = VMConst.DETAIL_URL + softId;

		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						soft = JsonUtils.jsonToBean(arg0, Soft.class);

						// 初始化积分领取按钮
						initBtn_Intergral();

						iv_softImage = (ImageView) findViewById(R.id.iv_softImage);

						ImageLoader.getInstance().displayImage(
								VMConst.URL + soft.getImageUrl(), iv_softImage,
								MyDisplayImageOptions.getInstance());

						tv_softName.setText(soft.getName());

						tv_softdownload.setText(Integer.toString(soft
								.getDownload()));
						//
						// tv_version.setText(soft.getVersion());
						if (soft.getSize() != null) {
							float size = soft.getSize();
							DecimalFormat decimalFormat = new DecimalFormat(
									".00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
							String shotSize = decimalFormat.format(size);// format
																			// 返回的是字符串
							tv_soft_size.setText(shotSize + "M");
						}
						if (soft.getStar() != null) {
							float fstar = soft.getStar();
							rb_star.setRating(fstar / 2);
						}
						// collection.setImageurl(soft.getImageUrl());
						// collection.setName(soft.getName());
						// collection.setSoftId(soft.getId());
						// collection.setSize(soft.getSize());
						// collection.setStar(soft.getStar());
						CurrentSoft.SOFTID = soft.getId();
						CurrentSoft.SOFTIMG = soft.getImageUrl();
						CurrentSoft.SOFTNAME = soft.getName();
						CurrentSoft.SOFTSIZE = soft.getSize();
						CurrentSoft.SOFTSTAR = soft.getStar();
						initFragment();
						new Thread(new Runnable() {
							@Override
							public void run() {
								spandTimeMethod();// 耗时的方法
								handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
							}

						}).start();
						// UIHelper.hideDialogForLoading();
						// rlayout_introduce.setVisibility(View.VISIBLE);
						// llayout_group.setVisibility(View.VISIBLE);
					}
				}, null);

		mQueue.add(jsonObjectRequest);
	}

	/**
	 * 
	 */
	private void initBtn_Intergral() {

		if (btnType == 3) {
			btn_getIntergral.setText("领取积分");
			btn_getIntergral.setOnClickListener(btn_getIntergralListener);
		} else if (btnType == 4) {
			btn_getIntergral.setText("已领取");
		} else {
			btn_getIntergral.setVisibility(View.GONE);
		}

		// 判断是否为积分专区软件
		// if (soft.getTypeId() == 3) {
		// btn_getIntergral.setVisibility(View.INVISIBLE);
		// } else {
		// btn_getIntergral.setVisibility(View.VISIBLE);
		// if (CurrentUser.USERID != null) {
		// String url = VMConst.REQUEST_URL + "ifGet?softId="
		// + soft.getId() + "&userId=" + CurrentUser.USERID;
		// StringRequest ifGetRequest = new StringRequest(url,
		// new Listener<String>() {
		//
		// @Override
		// public void onResponse(String response) {
		// if (response.equals("已领取")) {
		// btn_getIntergral.setText("已领取");
		// } else {
		// btn_getIntergral
		// .setOnClickListener(btn_getIntergralListener);
		// }
		// }
		// }, new ErrorListener() {
		//
		// @Override
		// public void onErrorResponse(VolleyError error) {
		// }
		// });
		// mQueue.add(ifGetRequest);
		//
		// // btn_getIntergral.setOnClickListener(btn_getIntergralListener);
		// } else {
		// btn_getIntergral.setOnClickListener(btn_getIntergralListener);
		// // Toast toast = Toast.makeText(DetailActivity.this, "请先登录",
		// // 500);
		// // toast.setGravity(Gravity.CENTER, 0, 0);
		// // toast.show();
		// }
		// }

		// }
	}

	/**
	 * 领取积分
	 */
	OnClickListener btn_getIntergralListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			String url = VMConst.REQUEST_URL + "getDownIntergral?softId="
					+ soft.getId() + "&userId=" + CurrentUser.USERID;
			StringRequest ifGetRequest = new StringRequest(url,
					new Listener<String>() {

						@Override
						public void onResponse(String response) {
							if (response.contains("领取成功")) {
								Toast toast = Toast.makeText(
										DetailActivity.this, "领取成功", 500);
								toast.setGravity(Gravity.CENTER, 0, 0);
								toast.show();
								btn_getIntergral.setText("已领取");
								CurrentUser.INTERGRAL += 10;
							} else {
								Toast toast = Toast.makeText(
										DetailActivity.this, response, 500);
								toast.setGravity(Gravity.CENTER, 0, 0);
								toast.show();
							}
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
						}
					});
			mQueue.add(ifGetRequest);

		}
	};

	OnClickListener btn_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.rbtn_introduce:
				nsvp.setCurrentItem(0);
				break;
			case R.id.rbtn_comments:
				nsvp.setCurrentItem(1);
				break;
			case R.id.rbtn_related:
				// tabHost.setCurrentTab(2);
				break;

			default:
				break;
			}
		}
	};

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (a == 0) {
				onBackPressed();
			} else {
				Intent intent = new Intent(DetailActivity.this,
						CollectionActivity.class);
				startActivity(intent);
				finish();
			}
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {

		ThreadManager.stopSendMessage(softId);
		if (a == 0) {
			super.onBackPressed();
		} else {
			Intent intent = new Intent(DetailActivity.this,
					CollectionActivity.class);
			startActivity(intent);
			finish();
		}
		System.out.println("按下了back键   onBackPressed()");
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 安装
	 */
	public void install() {
		File apkfile = new File(StringUtil.getSdApkUrl(soft.getName()));
		if (!apkfile.exists()) {
			return;
		}
		if (CurrentSetting.autoinstall == 1) {
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");
			startActivity(i);
		}
	}

	private void spandTimeMethod() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
			// pd.dismiss();// 关闭ProgressDialog
			UIHelper.hideDialogForLoading();
			rlayout_introduce.setVisibility(View.VISIBLE);
			llayout_group.setVisibility(View.VISIBLE);
			viewpager.setVisibility(View.VISIBLE);
			super.handleMessage(msg);
		}

	};

	public void addRecord() {
		int number = Integer.parseInt(tv_softdownload.getText().toString()) + 1;
		tv_softdownload.setText(Integer.toString(number));
	}

	@Override
	protected void onStop() {
		// this.get

		ViewGroup root = (ViewGroup) this.getWindow().getDecorView()
				.findViewById(android.R.id.content);

		BitmapUtil.relaseAllBitmap(root);

		// rl_detail = (RelativeLayout) findViewById(R.id.rl_detail);
		// for (int i = 0; i < rl_detail.getChildCount(); i++) {
		// ViewGroup v = rl_detail.getChildAt(i);
		//
		// if (v instanceof ImageView) {
		//
		// BitmapUtil.releaseImageView((ImageView) v);
		// }
		// }
		super.onStop();

	};

}
